package com.coolwar.design.strategy;


import cn.hutool.core.lang.ClassScaner;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Coolwar
 * DCL（双检查锁机制）单例模式
 * volatile 禁止指令重排，保证先初始化instance的构造器，再将instance对象指向分配的内存空间（注意到这步时instance就非null了）
 */
public class HandelRoute {

    private static volatile Map<String, BaseHandle> instance;

    public static Map<String, BaseHandle> getInstance() {
        if (instance == null) {
            synchronized (HandelRoute.class) {
                if (instance == null) {
                    instance = new HashMap<>(4);
                    ClassScaner.scanPackage("com.coolwar.design.strategy").forEach(aClass -> {
                        try {
                            HandleAnn annotation = aClass.getAnnotation(HandleAnn.class);
                            if (annotation == null) {
                                return;
                            }
                            Object o = aClass.newInstance();
                            if (o instanceof BaseHandle) {
                                instance.put(annotation.value(), (BaseHandle) o);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    return instance;
                }
            }
        }
        return instance;
    }

    public static void exe(String hello) {
        HandelRoute.getInstance().get(hello).handle();
    }
}









